package com.wlhse.service.impl;

import com.github.pagehelper.PageHelper;
import com.wlhse.dao.SupervisionTaskDao2;
import com.wlhse.dao.UserDao;
import com.wlhse.dto.*;
import com.wlhse.dto.inDto.CheckRecordInDto;
import com.wlhse.dto.inDto.SupervisionScope;
import com.wlhse.dto.inDto.SupervisionScopeInDto;
import com.wlhse.dto.outDto.CheckRecordRectRecord;
import com.wlhse.entity.*;
import com.wlhse.service.SupervisionTaskService2;
import com.wlhse.util.TreeUtil;
import com.wlhse.util.state_code.CodeDict;
import com.wlhse.util.state_code.NR;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.*;

@Service
public class SupervisionTaskServiceImpl2 implements SupervisionTaskService2 {
    @Resource
    private SupervisionTaskDao2 supervisionTaskDao2;

    @Resource
    private UserDao userDao;

    @Override
    public String querryTaskTime(String id, String date) {
            return NR.r(supervisionTaskDao2.querryTaskTime(date,id));
    }

    @Override
    public String querryCheckLevel() {
        return NR.r(supervisionTaskDao2.querryCheckLevel());
    }

    @Override
    public String querryLoginName(String id) {
        return NR.r(userDao.getUserName(id));
    }

    @Override
    public String querryCheckList() {
        return NR.r(supervisionTaskDao2.querryCheckList());
    }

    @Override
    public String querryCheckProject(String id) {
        return NR.r(supervisionTaskDao2.querryCheckProject(id));
    }

    @Override
    public String querryCheckItem(String projectCode, String listID) {
        return NR.r(supervisionTaskDao2.querryCheckItem(projectCode,listID));
    }

    @Override
    public String querryProblemType(String projectCode,String listID) {
        return NR.r(supervisionTaskDao2.querryProblemType(projectCode,listID));
    }

    @Override
    public String querryProblemRank(String projectCode,String listID) {
        return NR.r(supervisionTaskDao2.querryProblemRank(projectCode,listID));
    }

    @Override
    public String querryProblemSourcr() {
        return NR.r(supervisionTaskDao2.querryProblemSourcr());
    }

    @Override
    public String querryProblemGist(String projectCode, String listID) {
        return NR.r(supervisionTaskDao2.querryProblemGist(projectCode,listID));
    }

    @Override
    public String querryTaskDetail(String id) {
        return NR.r(supervisionTaskDao2.querryTaskDetail(id));
    }

    @Override
    public String querryStaffTask(SupervisionTaskDto supervisionTaskDto) {
        List<String > codes=supervisionTaskDao2.querryTaskCode(supervisionTaskDto);
        if(codes==null||codes.size()<=0){
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.SELECT_FAILE,null,null,0,0);
        }
        List<SupervisionTaskDetailPojo2> tasks=supervisionTaskDao2.querryStaffTask(codes);
        //把相同检查类型放一起
        List<SupervisionTaskDetailPojo2> team = new LinkedList<>();//作业队
        List<SupervisionTaskDetailPojo2> group = new LinkedList<>();//配属班组
        List<SupervisionTaskDetailPojo2> location = new LinkedList<>();//重点要害部位及固定场所
        List<SupervisionTaskDetailPojo2> key= new LinkedList<>();//专项检查
        List<SupervisionTaskDetailPojo2> check = new LinkedList<>();//关键环节
        for (SupervisionTaskDetailPojo2 task : tasks) {
            if ("作业队".equals(task.getTaskType())){
                team.add(task);
            }else if("配属班组".equals(task.getTaskType())){
                group.add(task);
            }else if("重点要害部位及固定场所".equals(task.getTaskType())){
                location.add(task);
            }else if("专项检查".equals(task.getTaskType())){
                key.add(task);
            }else {
                check.add(task);
            }
        }
        team.addAll(group);
        team.addAll(location);
        team.addAll(key);
        team.addAll(check);
        return NR.r(team);
    }

    @Override
    public String querryTaskContent(String code) {
        List<TaskContentPojo> taskContentPojos=supervisionTaskDao2.querryTaskContent(code);
        TaskContentsPojo Node=new TaskContentsPojo();
        for(TaskContentPojo task:taskContentPojos){//树状结构  第一层  根节点
            if(task.getDictCode().length()==4){
                Node.setDictCode(task.getDictCode());
                Node.setName(task.getName());
                break;
            }
        }
        for(TaskContentPojo task:taskContentPojos) {//树状结构  第二层
            if(task.getDictCode().length()==6){
                TaskContentsPojo firstChild=new TaskContentsPojo(task.getDictCode(),task.getName());
                if(Node.getChildNodes()==null){
                    Node.setChildNodes(new LinkedList<>());
                }
                Node.getChildNodes().add(firstChild);
            }
        }
        for(TaskContentPojo task:taskContentPojos) {//树状结构 第三层
            if(task.getDictCode().length()==8){
                if(Node.getChildNodes()!=null){
                    for(TaskContentsPojo firstChild:Node.getChildNodes()){//默认根节点 一定有 孩子节点
                        if(firstChild.getDictCode().equals(task.getDictCode().substring(0,6))){
                            TaskContentsPojo secondChild=new TaskContentsPojo(task.getDictCode(),task.getName());
                            if(firstChild.getChildNodes()==null){
                                firstChild.setChildNodes(new LinkedList<>());
                            }
                            firstChild.getChildNodes().add(secondChild);
                            break;
                        }
                    }
                }
            }
        }
        for(TaskContentPojo task:taskContentPojos) {//树状结构 第四层
            if(task.getDictCode().length()==10){
                int flag=0;
                for(TaskContentsPojo firstChild:Node.getChildNodes()){
                    if(firstChild.getChildNodes()!=null){// 判断是否有孩子节点
                        List<TaskContentsPojo> secondChilds=firstChild.getChildNodes();
                        if(flag==1){
                            break;
                        }
                        for(TaskContentsPojo secondChild:secondChilds){
                            if(secondChild.getDictCode().equals(task.getDictCode().substring(0,8))){
                                TaskContentsPojo thirdChild=new TaskContentsPojo(task.getDictCode(),task.getName());
                                if(secondChild.getChildNodes()==null){
                                    secondChild.setChildNodes(new LinkedList<>());
                                }
                                secondChild.getChildNodes().add(thirdChild);
                                flag=1;
                                break;
                            }
                        }
                    }
                }
            }
        }
        for(TaskContentPojo task:taskContentPojos) {//树状结构 第五层
            if(task.getDictCode().length()==12){
                int flag=0;
                for(TaskContentsPojo firstChild:Node.getChildNodes()){
                    if(firstChild.getChildNodes()!=null){
                        List<TaskContentsPojo> secondChilds=firstChild.getChildNodes();
                        if(flag==1){
                            break;
                        }
                        for(TaskContentsPojo secondChild:secondChilds){
                            if(secondChild.getChildNodes()!=null){
                                List<TaskContentsPojo> thirdChilds=secondChild.getChildNodes();
                                if(flag==1){
                                    break;
                                }
                                for(TaskContentsPojo thirdChild:thirdChilds){
                                    if(thirdChild.getDictCode().equals(task.getDictCode().substring(0,10))){
                                        TaskContentsPojo fouthChild=new TaskContentsPojo(task.getDictCode(),task.getName());
                                        if(thirdChild.getChildNodes()==null){
                                            thirdChild.setChildNodes(new LinkedList<>());
                                        }
                                        thirdChild.getChildNodes().add(fouthChild);
                                        flag=1;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return NR.r(Node);
    }

    @Override
    public String querryCheckTable(String code) {
        CheckTablePojo checkTable=new CheckTablePojo();
        List<CheckListItemPojo> items=new LinkedList<>();
        List<CheckTablePojo> checkTablePojo=supervisionTaskDao2.querryCheckTable(code);
        for(CheckTablePojo table:checkTablePojo){//查询出不同表中的全部节点
            List<CheckListItemPojo> list=supervisionTaskDao2.querryCheckListItem(table.getCheckListCode(),table.getStartSerialNumber(),table.getEndSerialNumber());
            String parentCode="";
            String id="";
            int min=100;
            for(CheckListItemPojo itemPojo:list){//寻找表中最小父节点应该是多少
                int num=Integer.parseInt(itemPojo.getCheckListItemCode().substring(0,2));
                if(num<min){
                    min=num;
                    parentCode=itemPojo.getCheckListItemCode().substring(0,2);
                    id=itemPojo.getCheckListID();
                }
            }
            int flag=0;
            for(CheckListItemPojo itemPojo:list){//检查是否有最小的父节点
                if(itemPojo.getCheckListItemCode().length()==2){
                    if(itemPojo.getCheckListItemCode().equals(parentCode)){
                        flag=1;
                    }
                }
            }

            if(flag==0){//如果没有这加上
                CheckListItemPojo parent=supervisionTaskDao2.querrtRootItem(id,parentCode);
                if(parent!=null)list.add(0,parent);
            }
            items.addAll(list);
            System.out.println(list);
        }
        //树状结构
        CheckTablePojo checkTable1=getTreeTable(checkTable,items);
        System.out.println("----------------");
        System.out.println(checkTable1);
        return NR.r(checkTable1);
    }

    @Override
    public String querryCheckTableBySearch(String code, String value) {
        CheckTablePojo checkTable=new CheckTablePojo();
        List<CheckListItemPojo> items=new LinkedList<>();
        List<CheckTablePojo> checkTablePojo=supervisionTaskDao2.querryCheckTable(code);
        for(CheckTablePojo table:checkTablePojo){//查询出不同表中的全部节点
            List<CheckListItemPojo> list=supervisionTaskDao2.querryCheckListItemBySearch(table.getCheckListCode(),table.getStartSerialNumber(),table.getEndSerialNumber(),value);
            String parentCode="";
            String id="";
            int min=100;
            for(CheckListItemPojo itemPojo:list){//寻找表中最小父节点应该是多少
                int num=Integer.parseInt(itemPojo.getCheckListItemCode().substring(0,2));
                if(num<min){
                    min=num;
                    parentCode=itemPojo.getCheckListItemCode().substring(0,2);
                    id=itemPojo.getCheckListID();
                }
            }
            int flag=0;
            for(CheckListItemPojo itemPojo:list){//检查是否有最小的父节点
                if(itemPojo.getCheckListItemCode().length()==2){
                    if(itemPojo.getCheckListItemCode().equals(parentCode)){
                        flag=1;
                    }
                }
            }
            if(flag==0){//如果没有这加上
                CheckListItemPojo parent=supervisionTaskDao2.querrtRootItem(id,parentCode);
                list.add(0,parent);
            }
            items.addAll(list);
        }
        //树状结构
        CheckTablePojo checkTable1=getTreeTable(checkTable,items);
        return NR.r(checkTable1);
    }

    @Override
    @Transactional
    public String addActuaInspectionTimes(String code, String taskitem) {
        List<CheckRecordPojo> checkRecordPojos=new ArrayList<>();
        try{
            checkRecordPojos=supervisionTaskDao2.queryCheckRecordsBySupervisionTaskDetail2ID(code,taskitem);
        }catch (Exception e){//supervisiontaskdetail2表中不能存在重复任务
            return NR.r(CodeDict.UPDATE_FAILE_CASE,"更新失败，存在重复任务");
        }

        for(CheckRecordPojo checkRecordPojo:checkRecordPojos){
            String status=supervisionTaskDao2.queryRectStatus(checkRecordPojo.getCheckRecordID().toString());
            if("是".equals(status)){//立即整改检查记录增加整改记录
                List<CheckRecordPojo> t=new ArrayList<>();
                t.add(checkRecordPojo);
                supervisionTaskDao2.addRectRecord(t);
            }
        }
        supervisionTaskDao2.changeRecordStatus(code,taskitem);//更改记录状态
        if(supervisionTaskDao2.addActuaInspectionTimes(code,taskitem)>0){
            //判断任务是否完成
            List taskCode=new LinkedList<String>();
            taskCode.add(code);
            List<SupervisionTaskDetailPojo2> supervisionTaskDetailPojo2s=supervisionTaskDao2.querryStaffTask(taskCode);
            boolean flag=true;
            for (SupervisionTaskDetailPojo2 supervisionTaskDetailPojo2 : supervisionTaskDetailPojo2s) {
                if(Integer.parseInt(supervisionTaskDetailPojo2.getActuaInspectionTimes())
                        <Integer.parseInt(supervisionTaskDetailPojo2.getPlannedInspectionTimes())){
                    flag=false;
                    break;
                }
            }
            if(flag){//所有任务都完成，则更改任务状态
                supervisionTaskDao2.updateSupervisionTaskStatus(code);
            }
            return NR.r();
        }else{
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.UPDATE_FAILE,null,null,0,0);
        }
    }

    @Override
    public String querryHazardFactors(String code) {
        String hazardFactors;
        hazardFactors=supervisionTaskDao2.querryHazardFactor(code);
        if(hazardFactors==null||"".equals(hazardFactors)){
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.SELECT_FAILE,null,null,0,0);
        }else {
            return NR.r(hazardFactors);
        }

    }

    @Override
    public String queryUserMessgaer(String id) {
        Message2 message2=supervisionTaskDao2.queryUserMessgaer(id);
        if(message2==null){
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.SELECT_FAILE,null,null,0,0);
        }else{
            return NR.r(supervisionTaskDao2.queryUserMessgaer(id));
        }
    }

    @Override
    public String addUserMessager(InMessage2 message2) {
        Integer flag= supervisionTaskDao2.addUserMessager(message2);
        if(flag>0){
            return NR.r();
        }else {
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.INSERT_FAILE,null,null,0,0);
        }
    }

    @Override
    @Transactional
    public String addCause(){
        List<CheckListItemPojo> checkListItemPojos=supervisionTaskDao2.getCause();
        int count=0;
        for(CheckListItemPojo checkListItemPojo:checkListItemPojos){
            String cause=checkListItemPojo.getCause();
            if(cause!=null){
                String str="0031";
                count++;
                if(count<10){
                    str=str+"0"+count;
                }else{
                    str=str+count;
                }
                supervisionTaskDao2.addCause(str,cause);
            }

        }
        return NR.r();
    }

    public void formatEmployee(List<EmployeePojo> employeePojos){
        for(EmployeePojo employeePojo:employeePojos){
            String info=employeePojo.getName()+"(";
            if(employeePojo.getPosition()!=null){
                info+=employeePojo.getPosition();
            }
            info+="|";
            if(employeePojo.getCompanyCode()!=null){
                String secondCode=employeePojo.getCompanyCode().substring(0,4);
                String secondName = supervisionTaskDao2.queryCompanyName(secondCode);
                info+=secondName;
                if(employeePojo.getCompanyCode().length()>4){
                    String thirdCode=employeePojo.getCompanyCode().substring(0,6);
                    String thirdName = supervisionTaskDao2.queryCompanyName(thirdCode);
                    info+="/"+thirdName;
                }
                if(employeePojo.getCompanyCode().length()>6){
                    String fourthName = supervisionTaskDao2.queryCompanyName(employeePojo.getCompanyCode());
                    info+="/"+fourthName;
                }
            }
            info+=")";
            employeePojo.setName(info);
        }
    }

    public void formatEmployee2(List<HSECheckPerson> hseCheckPeoples){
        for(HSECheckPerson hseCheckPerson:hseCheckPeoples){
            String info=hseCheckPerson.getName()+"(";
            if(hseCheckPerson.getPosition()!=null){
                info+=hseCheckPerson.getPosition();
            }
            info+="|";
            info+=hseCheckPerson.getCompanyName();
            info+=")";
            hseCheckPerson.setInfo(info);
        }
    }

    public void formatEmployee3(List<HSECheckPerson> hseCheckPeoples,String parentCompany){
        for(HSECheckPerson hseCheckPerson:hseCheckPeoples){
            String info=hseCheckPerson.getName()+"(";
            if(hseCheckPerson.getPosition()!=null){
                info+=hseCheckPerson.getPosition();
            }
            info+="|";
            info+=hseCheckPerson.getCompanyName();
            info+=")";
            hseCheckPerson.setInfo(info);
            if (parentCompany!=null){
                hseCheckPerson.setParentCompany(parentCompany);
            }
        }
    }

    @Override
    public String querySubComEmployee(String code) {
        List<EmployeePojo> employeePojos=supervisionTaskDao2.querySubComEmployee(code);
        formatEmployee(employeePojos);
        return NR.r(employeePojos);
    }

    @Override
    public String queryHSECheckPerson() {
        List<HSECheckPerson> hseCheckPeoples=supervisionTaskDao2.querySubComEmployee2();
        formatEmployee2(hseCheckPeoples);
        return NR.r(hseCheckPeoples);
    }

    @Override
    public String queryCheckpersonByCode(String companyCode) {
        String parentCompany=null;
        if(companyCode.length()>4){
            //只需要前四位code来获取公司
            String parentCode=companyCode.substring(0,4);
            parentCompany=supervisionTaskDao2.queryNameByCode(parentCode);
        }

        List<HSECheckPerson> hseCheckPeoples=supervisionTaskDao2.queryCheckpersonByCode(companyCode);
        System.out.println(hseCheckPeoples.size());
        formatEmployee3(hseCheckPeoples,parentCompany);
        return NR.r(hseCheckPeoples);
    }

    @Override
    public String querySubComUserEmployee(String code) {
        List<EmployeePojo> employeePojos=supervisionTaskDao2.querySubComUserEmployee(code);
        formatEmployee(employeePojos);
        return NR.r(employeePojos);
    }

    @Override
    public String queryManageEmployee(String userID) {
        List<EmployeePojo> employeePojos=supervisionTaskDao2.queryManageEmployee(userID);
        formatEmployee(employeePojos);
        return NR.r(employeePojos);
    }

    @Override
    public String querySubComEmployeeByType(String code,String userID) {
        String role = supervisionTaskDao2.queryRodeById(userID);
        if("2007".equals(role)){
            String station = supervisionTaskDao2.queryEmployeeStation(userID);
            if("主任".equals(station)){
                List<EmployeePojo> employeePojos=supervisionTaskDao2.directorQuerySubComEmployee(code);
                formatEmployee(employeePojos);
                return NR.r(employeePojos);
            }else if("副主任".equals(station)){
                List<EmployeePojo> employeePojos=supervisionTaskDao2.deputyDirectorQuerySubComEmployee(code);
                formatEmployee(employeePojos);
                return NR.r(employeePojos);
            }else if("执行管理".equals(station)|"技术管理".equals(station)){
                List<EmployeePojo> employeePojos=supervisionTaskDao2.technicalManagerQuerySubComEmployee(code);
                formatEmployee(employeePojos);
                return NR.r(employeePojos);
            }else{
                return NR.r();
            }
        }else if("2008".equals(role)){
            List<EmployeePojo> employeePojos=supervisionTaskDao2.querySubComUserEmployee(code);
            formatEmployee(employeePojos);
            return NR.r(employeePojos);
        }else {
            return NR.r("当前角色没有权限访问");
        }

    }

    @Override
    public String queryCheckRecordByID(CheckRecordInDto checkRecordInDto,String id) {
        Integer total = supervisionTaskDao2.queryCheckRecordCountsByID(id, checkRecordInDto);
        if (checkRecordInDto.getType().equals("all")){
            return NR.r(supervisionTaskDao2.queryCheckRecordByID(id, checkRecordInDto),total,1);
        }
        //分页查询
        PageHelper.startPage(checkRecordInDto.getPageIdx(), checkRecordInDto.getPageSize());
        List<CheckRecordRectRecord> checkRecordRectRecords = supervisionTaskDao2.queryCheckRecordByID(id, checkRecordInDto);
        return NR.r(checkRecordRectRecords,total,checkRecordInDto.getPageIdx());
    }

    @Override
    @Transactional
    public String updateCheckRecordByRecordID(CheckRecordDto checkRecordDto) {

        //修改检查记录 记录状态
        checkRecordDto.setRecordStatus("录入");
        Integer flag = supervisionTaskDao2.updateCheckRecordByRecordID(checkRecordDto);
        CheckRecordDto checkRecordDto1=supervisionTaskDao2.queryCheckRecordByRecordID(checkRecordDto.getCheckRecordID());

        //统计检查记录条数
        Integer count=supervisionTaskDao2.countCheckRecord(checkRecordDto1);

        if(count==0){//整改完成，整改次数加一
            supervisionTaskDao2.addActuaInspectionTimes2(checkRecordDto1);

            //判断任务是否完成
            List taskCode=new LinkedList<String>();
            taskCode.add(checkRecordDto1.getSupervisionTaskCode());
            List<SupervisionTaskDetailPojo2> supervisionTaskDetailPojo2s=supervisionTaskDao2.querryStaffTask(taskCode);
            boolean flag3=true;
            for (SupervisionTaskDetailPojo2 supervisionTaskDetailPojo2 : supervisionTaskDetailPojo2s) {
                if(Integer.parseInt(supervisionTaskDetailPojo2.getActuaInspectionTimes())
                        <Integer.parseInt(supervisionTaskDetailPojo2.getPlannedInspectionTimes())){
                    flag3=false;
                    break;
                }
            }
            if(flag3){//所有任务都完成，则更改任务状态
                supervisionTaskDao2.updateSupervisionTaskStatus(checkRecordDto1.getSupervisionTaskCode());
            }
        }

        if(flag>0){
            return NR.r();
        }else {
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.UPDATE_FAILE,null,null,0,0);
        }

    }

    @Override
    public String deleteCheckRecordByID(String id) {
        Integer flag = supervisionTaskDao2.deleteCheckRecordByID(id);
        if(flag>0){
            return NR.r();
        }else {
            return NR.r(CodeDict.CODE_MESSAGE,-1,CodeDict.DELETE_FAILE,null,null,0,0);
        }
    }

    @Override
    @Transactional
    public String updateSupervisionScope(SupervisionScopeInDto supervisionScopeInDtos) {
        List<SupervisionScope> supervisionScopes = supervisionScopeInDtos.getSupervisionScope();
        List<SupervisionScope> supervisionScopes1=new ArrayList<>();
        List<SupervisionScope> supervisionScopes2=new ArrayList<>();
        supervisionTaskDao2.deleteScopeByStaffID(supervisionScopeInDtos.getStaffID());
        for (SupervisionScope supervisionScope : supervisionScopes) {
            supervisionScope.setStaffID(supervisionScopeInDtos.getStaffID());
            if("专项检查".equals(supervisionScope.getTaskType())||"关键环节".equals(supervisionScope.getTaskType())){
                supervisionScopes2.add(supervisionScope);
            }else {
                supervisionScopes1.add(supervisionScope);
            }
        }
        if(supervisionScopes1.size()>0){
            supervisionTaskDao2.addSupervisionScopes(supervisionScopes1);
        }
        if (supervisionScopes2.size()>0){
            supervisionTaskDao2.addSupervisionScopes2(supervisionScopes2);
        }
        
        return NR.r();
    }

    @Override
    public String queryUserByRoleCode(String code) {
        return NR.r(supervisionTaskDao2.queryUserByRoleCode(code));
    }

    @Override
    public String queryAreaName() {
        return NR.r(supervisionTaskDao2.queryAreaName());
    }

    public CheckTablePojo getTreeTable(CheckTablePojo checkTablePojo,List<CheckListItemPojo> checkListItemPojos){
        List<CheckListParentNodespojo> nodes=new LinkedList<>();
        for(CheckListItemPojo item:checkListItemPojos){//树状结构
            if(item.getCheckListItemCode().length()==2){
                CheckListParentNodespojo checkListParentNodespojo=
                        new CheckListParentNodespojo(item.getCheckListID(),item.getCheckListItemCode(),item.getCheckListItemName(),item.getGist(),item.getHazardFactorType(),item.getProblemRank(),item.getHseFactor(),item.getScore(),item.getInsertDateCode(),item.getStatus());
                nodes.add(checkListParentNodespojo);
            }
        }
        for(CheckListItemPojo item:checkListItemPojos){//树状结构 封装子节点
            if(item.getCheckListItemCode().length()>2){
                for(CheckListParentNodespojo node:nodes){
                    if(item.getCheckListItemCode().substring(0,2).equals(node.getCheckListItemCode())&&
                            item.getCheckListID().equals(node.getCheckListID())){
                        node.getChildNodes().add(item);
                        break;
                    }
                }
            }
        }
        if (checkTablePojo!=null){
            checkTablePojo.setItems(nodes);
        }
        return checkTablePojo;
    }

    @Override
    public String queryCompleteCheckTable(String code) {
        CheckTablePojo checkTablePojo = supervisionTaskDao2.querryCheckListInfo(code);
        List<CheckListItemPojo> checkListItemPojos = supervisionTaskDao2.querryCompleteCheckListItem(code);

        CheckTablePojo checkTable=getTreeTable(checkTablePojo,checkListItemPojos);
        if (checkTable!=null){
            return NR.r(checkTable);
        }
        return NR.r(CodeDict.SELECT_FAILE,"检查表代码不存在！");
    }

    @Override
    public String queryUntreatedSupervisionArea(String areaID, String companyType, String staffID) {
        return NR.r(supervisionTaskDao2.queryUntreatedSupervisionArea(areaID,companyType,staffID));
    }

    @Override
    public String queryUntreatedCheckType(String code, String staffID) {
        return NR.r(supervisionTaskDao2.queryUntreatedCheckType(code,staffID));
    }

    @Override
    public String querySupervisionAreaCompanyByArea(String areaName, String areaCode) {
        List<SuperVisionAreaCompany> superVisionAreaCompanies = supervisionTaskDao2.querySupervisionAreaCompanyByArea(areaName, areaCode);
        List<SuperVisionAreaCompany> team=new ArrayList<>();//作业队
        List<SuperVisionAreaCompany> group=new ArrayList<>();//配属班组
        List<SuperVisionAreaCompany> location=new ArrayList<>();//重点要害部位及固定场所
        for (SuperVisionAreaCompany superVisionAreaCompany : superVisionAreaCompanies) {
            if("作业队".equals(superVisionAreaCompany.getCompanyType())){
                team.add(superVisionAreaCompany);
            }else if ("配属班组".equals(superVisionAreaCompany.getCompanyType())){
                group.add(superVisionAreaCompany);
            }else if ("重点要害部位及固定场所".equals(superVisionAreaCompany.getCompanyType())){
                location.add(superVisionAreaCompany);
            }
        }

        return NR.task(team,group,location);
    }

    @Override
    public String queryUntreatedCompanies(String name, String code) {
        List<CompanyPojo> companyPojos;
        if("".equals(name)&&"".equals(code)){
            companyPojos=supervisionTaskDao2.queryUntreatedCompanies();
        }else {
            companyPojos=supervisionTaskDao2.queryUntreatedCompaniesByArea(name,code);
        }
        //树状返回
        TreeUtil treeUtil = new TreeUtil();
        List<TreeDto> companyTree = treeUtil.getCompanyTree(companyPojos);

        return NR.r(companyTree);
    }

    @Override
    @Transactional
    public String updateSuperVisionAreaCompany(String code, List<SuperVisionAreaCompany> superVisionAreaCompanies) {
        Integer flag1 = supervisionTaskDao2.deleteSupervisionAreaCompany(code);
        Integer flag2 = supervisionTaskDao2.addSupervisionAreaCompany(superVisionAreaCompanies);
        if (flag1>0&&flag2>0){
            return NR.r();
        }else {
            return NR.r(CodeDict.CODE_MESSAGE, -1, CodeDict.UPDATE_FAILE, null, null, 0, 0);
        }
    }

    @Override
    public String queryCheckType() {
        return NR.r(supervisionTaskDao2.queryCheckType());
    }

    @Override
    public String queryCheckRound() {
        return NR.r(supervisionTaskDao2.queryCheckRound());
    }

    @Override
    public String countProblemRank(CountProblemDto countProblemDto) {
        List<MonthProblemAnalysisPojo> monthProblemAnalysisPojos=null;
        List<String> fields = supervisionTaskDao2.queryField(countProblemDto.getFieldCode());//查询统计的字段
        List<String> workingNames = supervisionTaskDao2.queryField("0004");//查询岗位
        try {
            monthProblemAnalysisPojos = supervisionTaskDao2.countProblemRankByMonth(countProblemDto);
        }catch (Exception e){
            return NR.r(CodeDict.SELECT_FAILE,"统计字段不存在！");
        }
        for (String field : fields) {//补全统计字段
            boolean flag=true;
            for (MonthProblemAnalysisPojo monthProblemAnalysisPojo : monthProblemAnalysisPojos) {
                if(monthProblemAnalysisPojo.getField().equals(field)){
                    flag=false;
                    break;
                }
            }
            if (flag){
                MonthProblemAnalysisPojo monthProblemAnalysisPojo = new MonthProblemAnalysisPojo(field);
                monthProblemAnalysisPojos.add(monthProblemAnalysisPojo);
            }
        }

        HashMap<String, Object> restMap = new HashMap<>();

        Integer total=0;
        HashMap<String, Integer> countMap = new LinkedHashMap<>();
        LinkedList<SortNode> sortNodes = new LinkedList<>();
        //获取按统计数量排序的 List<(filed,count)>
        for (MonthProblemAnalysisPojo monthProblemAnalysisPojo : monthProblemAnalysisPojos) {
            total+=monthProblemAnalysisPojo.getTotals();
            Integer count = monthProblemAnalysisPojo.getTotals();
            String field = monthProblemAnalysisPojo.getField();
            if(sortNodes.size()==0){
                sortNodes.add(new SortNode(field,count));
            }else {
                boolean flag=true;
                for (SortNode sortNode : sortNodes) {//升序插入排序
                    if(sortNode.getCount()>count){
                        sortNodes.add(sortNodes.indexOf(sortNode),new SortNode(field,count));
                        flag=false;
                        break;
                    }
                }
                if(flag){
                    sortNodes.add(sortNodes.size(),new SortNode(field,count));
                }
            }
        }
        for (SortNode sortNode : sortNodes) {//按sortNode的顺序加入节点
            for (MonthProblemAnalysisPojo monthProblemAnalysisPojo : monthProblemAnalysisPojos) {
                String field = monthProblemAnalysisPojo.getField();
                if(sortNode.getFieldName().equals(field)){
                    countMap.put(monthProblemAnalysisPojo.getField(),monthProblemAnalysisPojo.getTotals());
                }
            }
        }
        restMap.put("数量统计",countMap);

        HashMap<String, String> percentMap = new LinkedHashMap<>();
        for (SortNode sortNode : sortNodes) {//按sortNode的顺序加入节点
            for (MonthProblemAnalysisPojo monthProblemAnalysisPojo : monthProblemAnalysisPojos) {
                String field = monthProblemAnalysisPojo.getField();
                if(sortNode.getFieldName().equals(field)){
                    String percentStr ="";
                    if(total!=0){
                        percentStr = String.format("%.2f", (double) monthProblemAnalysisPojo.getTotals() * 100 / total)+"%";
                    }else{
                        percentStr="0.00%";
                    }

                    percentMap.put(monthProblemAnalysisPojo.getField(),percentStr);
                }
            }
        }
        restMap.put("百分比统计",percentMap);

        ArrayList<Map<String, Object>> monthArr = new ArrayList<>();
        for(int i=1;i<=12;i++){//一年十二个月的数据
            HashMap<String, Object> monthMap = new HashMap<>();
            monthMap.put("月份",i);
            for (MonthProblemAnalysisPojo monthProblemAnalysisPojo : monthProblemAnalysisPojos) {
                monthMap.put(monthProblemAnalysisPojo.getField(),monthProblemAnalysisPojo.getMonthCount(i));
            }
            monthArr.add(monthMap);
        }
        restMap.put("月份统计",monthArr);

        //岗位统计
        ArrayList<Map<String, Object>> woringNameArr = new ArrayList<>();
        List<CountProblemByWorkingNameDto> workingNameAnalysis = supervisionTaskDao2.countProblemRankByWorkingName(countProblemDto);
        //某个岗位某个统计字段 的占比数
        for (String workingName : workingNames) {
            HashMap<String, Object> wokingNameMap = new HashMap<>();
            HashMap<String, Object> analysisFieldNameMap = new LinkedHashMap<>();
            wokingNameMap.put(workingName,analysisFieldNameMap);
            for (SortNode sortNode : sortNodes) {//按sortNode的顺序加入节点
                for (String field : fields) {
                    if(field.equals(sortNode.getFieldName())){//如果是当前节点才加入
                        boolean flag=true;
                        for (CountProblemByWorkingNameDto queryRes : workingNameAnalysis) {
                            if(workingName.equals(queryRes.getWorkingName())&&field.equals(queryRes.getField())){
                                analysisFieldNameMap.put(field,queryRes.getCount());
                                flag=false;
                                break;
                            }
                        }
                        if(flag){
                            analysisFieldNameMap.put(field,0);
                        }
                    }
                }
            }
//            for (String field : fields) {
//                boolean flag=true;
//                for (CountProblemByWorkingNameDto queryRes : workingNameAnalysis) {
//                    if(workingName.equals(queryRes.getWorkingName())&&field.equals(queryRes.getField())){
//                        analysisFieldNameMap.put(field,queryRes.getCount());
//                        flag=false;
//                        break;
//                    }
//                }
//                if(flag){
//                    analysisFieldNameMap.put(field,0);
//                }
//            }
            woringNameArr.add(wokingNameMap);
        }
        restMap.put("岗位统计",woringNameArr);



        return NR.r(restMap);

    }
}
